<template>
  <el-dialog
    :title="formData.id ? '编辑角色' : '新增角色'"
    :visible="showDialog"
    @close="closeFn"
  >
    <el-form ref="form" :model="formData" :rules="rules" label-width="120px">
      <el-form-item label="角色名称" prop="title">
        <el-input v-model="formData.title" />
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input v-model="formData.description" />
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-row type="flex" justify="center">
        <el-button size="small" type="primary" @click="submit">添加</el-button>
        <el-button size="small" @click="closeFn">取消</el-button>
      </el-row>
    </template>
  </el-dialog>
</template>
<script>
import { addRole, editRole, getRoles } from '@/api/role'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        title: '',
        description: ''
      },
      rules: {
        title: [
          { required: true, message: '角色名称不能为空！', trigger: 'blur' },
          { min: 1, max: 10, message: '角色名称长度1到10位!', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空！', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 调用接口
    async getRoles(id) {
      const res = await getRoles(id)
      // 数据回显
      this.formData = res.data
    },
    // 添加按钮
    submit() {
      // 表单校验 --- 校验同调用接口
      this.$refs.form.validate(async bool => {
        if (bool) {
          // 判断是新增还是编辑
          if (this.formData.id) {
            await editRole(this.formData)
          } else {
            await addRole(this.formData)
          }
          //   关闭弹窗
          //  子组件不能直接修改父组件元素，这样会导致父子组件数据不一致
          //   this.showDialog = false
          // 所以我们需要通过子传父技术通知父组件修改showDialog的值
          this.closeFn()
          // 更新浏览器中显示的列表
          this.$emit('updateEvent')
        }
      })
    },
    // 关闭弹框
    closeFn() {
      this.$emit('update:showDialog', false)
      // 清空表单
      this.formData = {
        title: '',
        description: ''
      }
      // 清空校验规则
      this.$refs.form.resetFields()
    }
  }
}
</script>
<style lang="scss">
.el-dialog__header {
    background: #66b1ff;

    .el-icon-close:before {
      color: #fff;
    }

    .el-dialog__title {
      color: #fff;
    }

  }
</style>
